package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
)

//命令行参数
var fileName = flag.String("f", "", "请输入需要编译的go文件的名称（default：test.go）")
var osType = flag.String("o", "mac", "需要编译成在哪个平台上运行的二进制文件：mac、linux、windwos三选一")
var outPut = flag.String("c", "./build/", "新生成的二进制文件生成在什么位置")
var newName = flag.String("n", "", "自定义二进制文件的名称（default：是您的文件名）")

func main() {
	// 把用户传递的命令行参数解析为对应变量的值
	flag.Parse()
	var CommandName string
	//切割文件名的字符串
	if len(*fileName) == 0 {
		fmt.Println("-t参数不能为空... \033[1;31;8m（输入 --help 查看命令详细用法）\033[0m")
		os.Exit(0)
	} else {
		//查看数据类型
		//fmt.Println("type:", reflect.TypeOf(fileName))
		//fmt.Println("type:", reflect.TypeOf(*fileName))
		//fmt.Println("type:", reflect.TypeOf(file))

		//获取提交过来的参数值
		var file = *fileName
		//切割文件名字符串
		if strings.Contains(file, ".go") {

			if strings.Contains(file, "/") {
				//安装/分割字符串
				var pathFileName = strings.Split(file, "/")
				var goFileName = strings.Split(pathFileName[len(pathFileName)-1], ".")
				CommandName = goFileName[0]
			} else {
				var goFileName = strings.Split(file, ".")
				CommandName = goFileName[0]
			}
			fmt.Println(CommandName)
		} else {
			println("您传入的不是一个go文件！")
		}

		//	创建目录
		var errMessage = os.MkdirAll("./build/", os.ModePerm)
		if errMessage != nil {
			fmt.Println(errMessage)
		} else {
			fmt.Println("成功创建 ./build/ 目录...")
		}

		//	判断第二个参数
		switch {
		case *osType == "linux":
			CommandName = CommandName + "-linux"
			fmt.Println(CommandName)

		case *osType == "windows" || *osType == "win":
			CommandName = CommandName + "-win"
			fmt.Println(CommandName)

		case *osType == "mac":
			CommandName = CommandName + "-mac"
			fmt.Println(CommandName)

		default:
			CommandName = CommandName + "-mac"
			fmt.Println(CommandName)
		}

		//判断-n参数是否为空
		if len(*newName) == 0 {
			//	如果-n参数为空，那么这里什么也不做
		} else {
			//	如果-n参数不为空，那么这里用用户传过来的名字替换默认处理好的名字
			CommandName = *newName
		}
		//执行command命令
		CommandName = *outPut + CommandName
		var cmd = exec.Command("go", "build", "-o", CommandName, *fileName)
		fmt.Println(cmd)
		if err3 := cmd.Run(); err3 != nil {
			log.Fatal(err3)
		}
	}
}
